import { CheckoutInfo, UserAddress } from '@/types/checkout'
import { apiRes } from '@/types/data'
import request from '@/utils/request'
import { defineStore } from 'pinia'

const useCheckoutStore = defineStore({
  id: 'checkout',
  state: () => ({
    checkoutInfo: {} as CheckoutInfo,
  }),
  actions: {
    async getCheckoutInfo() {
      const res = await request.get<apiRes<CheckoutInfo>>('/member/order/pre')
      this.checkoutInfo = res.data.result
    },
  },
  getters: {
    showAddress(): UserAddress | null {
      const userAddress = this.checkoutInfo.userAddresses
      if (userAddress.length) {
        const defaultAddress = userAddress.find((item) => item.isDefault === 0)
        if (defaultAddress) {
          return defaultAddress
        } else {
          return userAddress[0]
        }
      }
      return null
    },
  },
})

export default useCheckoutStore
